<template>
  <div>
    <!-- 搜索框 -->
    <van-search
      v-model="value"
      show-action
      placeholder="请输入搜索关键词"
      action-text="搜索"
      shape="round"
      @search="onSearch"
      @input="onSuggest"
    >
      <template #left>
        <van-icon
          @click="onClickLeft"
          class="icon"
          name="arrow-left"
        />
      </template>
      <template #action>
        <span
          @click="onSearch"
          class="search-btn"
        >搜索</span>
      </template>
    </van-search>

    <!-- 搜索建议列表 -->
    <div
      v-if="flag"
      class="loading"
    >
      <van-loading type="spinner" />
      loading
    </div>
    <van-list
      v-else-if="value.trim() && !flag"
      :finished="true"
    >
      <van-cell
        v-for="item in suggestionList"
        :key="item"
      >
        <van-icon name="search" />
        <span
          v-html="getHighLightHTML(item)"
          @click="onSearchResult(item)"
        />
      </van-cell>
    </van-list>
    <!-- 历史记录 -->
    <van-list
      v-else
      :finished="true"
    >
      <van-cell v-if="searchRecord.length">
        <template #title>
          <span class="title">历史记录</span>
        </template>
        <van-icon
          name="delete"
          size="18"
          @click="onSearchRecordRemove"
        />
      </van-cell>
      <van-cell
        v-for="(item, i) in searchRecord"
        :key="item"
        :title="item"
        @click="onSearchResult(item)"
      >
        <van-icon
          name="cross"
          size="18"
          @click="onSearchRecordItemRemove(i)"
        />
      </van-cell>
    </van-list>
  </div>
</template>

<script>
import {
  mapState,
  mapActions,
} from 'vuex';
import { uniq, debounce } from 'lodash';
export default {
  name: 'SearchPage',
  data() {
    return {
      value: '',
      loading: false,
      flag: false,
      searchRecord: JSON.parse(localStorage.getItem('searchRecord')) || [],
    };
  },
  computed: {
    // 集中导入model层数据
    ...mapState('search', [
      'suggestionList',
    ]),
  },
  methods: {
    ...mapActions('search', [
      'updateSuggestionList'
    ]),
    onClickLeft() {
      this.$router.go(-1);
    },
    onSearch() {
      if (!this.value.trim()) {
        return;
      }
      // 跳转搜索结果页面
      this.onSearchResult(this.value);
    },
    // onSuggest(value) {
    //   if (!this.value.trim()) {
    //     return;
    //   }
    //   this.updateSuggestionList(value);
    // },
    // 防抖 在输入后 1秒后再请求
    onDebounce: debounce(async function (value) {
      await this.updateSuggestionList(value);
      this.flag = false;
    }, 2000),
    onSuggest(value) {
      if (!value.trim()) {
        return;
      }
      this.flag = true;
      this.onDebounce(value);
    },
    getHighLightHTML(str) {
      // if (!str) {
      //   return '';
      // }
      return str.toLowerCase().replace(this.value, `<span class="highlight">${this.value}</span>`);
    },
    // 删除指定项
    onSearchRecordItemRemove(idx) {
      // 用于显示
      this.searchRecord.splice(idx, 1);
      // 用于记录
      localStorage.setItem('searchRecord', JSON.stringify(this.searchRecord));
      this.searchRecord = JSON.parse(localStorage.getItem('searchRecord'));
    },
    // 清空历史记录
    onSearchRecordRemove() {
      this.searchRecord = [];
      localStorage.removeItem('searchRecord');
    },

    // // 防抖
    // created() {
    //   // 更新历史记录
    //   this.searchRecord = JSON.parse(localStorage.getItem('searchRecord'))
    // },
    onSearchResult(item) {
      this.$router.push({
        path: '/search-result',
        query: {
          q: item,
        }
      })
      localStorage.setItem('searchRecord', JSON.stringify(uniq([item].concat(this.searchRecord))))
    }

  }
}
</script>

<style lang="less" scoped>
.icon {
  margin-right: 16px;
}
.search-btn {
  font-size: 14px;
  margin: 0 8px;
}
// 样式穿透
::v-deep .highlight {
  color:  red;
}
.title {
  color: #999;
}
.loading {
  color: #aaa;
  width: 100%;
  text-align: center;
  margin-top: 100px;
}
</style>
